import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/services.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:path/path.dart';
import 'package:super_tool_server/common/utils/log.dart';
import 'package:super_tool_server/model/config_info.dart';
import 'package:super_tool_server/resource/r.dart';

class ConfigManager {
  ConfigManager._();

  ConfigInfo _configInfo = ConfigInfo();
  String _localConfigPathKey = 'localConfigPathKey';
  String _localConfigPath = '';

  static ConfigManager? _instance;

  static ConfigManager getInstance() {
    if (_instance == null) {
      _instance = ConfigManager._();
    }
    return _instance!;
  }

  Future<void> loadConfig() async {
    try {
      _configInfo = ConfigInfo();
      var box = await Hive.openBox<String>('SuperToolServer');
      var localConfigPath = box.get(_localConfigPathKey);
      Future<void> loadAssetConfig() async {
        String jsonString = await rootBundle.loadString(getDefaultAssetConfig());
        _configInfo = ConfigInfo.fromJson(json.decode(jsonString));
        superLog.info("内置配置:  ${_configInfo?.localLogPath}");
      }

      if (localConfigPath != null && localConfigPath.isNotEmpty) {
        _localConfigPath = localConfigPath;
        File file = File(localConfigPath);
        if (await file.exists()) {
          String contents = await file.readAsString();
          _configInfo = ConfigInfo.fromJson(json.decode(contents));
          superLog.info("本地配置$localConfigPath:  ${_configInfo?.localLogPath}");
        } else {
          superLog.warning("本地配置文件不存在 $localConfigPath");
          await loadAssetConfig();
        }
      } else {
        _localConfigPath = getDefaultAssetConfig();
        await loadAssetConfig();
      }
    } catch (e, trace) {
      _localConfigPath = '配置解析失败 $_localConfigPath\n$e';
      superLog.severe("配置解析失败 $e\n$trace");
    }
  }

  Future<void> init() async {
    await loadConfig();
  }

  ConfigInfo getConfigInfo() {
    return _configInfo;
  }

  String getDefaultAssetConfig() {
    if (Platform.isMacOS) {
      return R.jsonConfigMac;
    } else {
      return R.jsonConfigWindows;
    }
  }

  String getLocalConfigPath() {
    return _localConfigPath.isNotEmpty ? _localConfigPath : getDefaultAssetConfig();
  }

  Future<void> setConfigPath(String path) async {
    var box = await Hive.openBox<String>('SuperTool');
    box.put(_localConfigPathKey, path);
    await loadConfig();
  }
}
